﻿using System;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using System.Web.UI;

/// <summary>
///sendweixin 的摘要说明
/// </summary>
public class sendweixin
{
    static string getmsg;//保存微信token凭证
    public static DateTime enddate;//保存超时时间  access_token的有效期目前为2个小时，需定时刷新
    static string jstoken;//保存微信jstoken凭证
    public static DateTime jsenddate;//js保存超时时间
    //string appid = "wxec31c99b6eb7f6c3";
    //string secret = "dfca031c1fd1816d364c7cd15a7a56b5";
    string appid = "wx6d3a3a25e9576db6";
    string secret = "3a444c2ec6dc28963fc6a20037a560cf";
    /// <summary>
    /// 获取wxtoken凭证
    /// </summary>
    /// <returns></returns>
    public string getwxtokan()
    {
        if (enddate == null || getmsg == null)
        {
            enddate = DateTime.Now;
        }
        if (DateTime.Now >= enddate)
        {
            getmsg = GetModel("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret + "");

        }
        //getmsg = GetModel("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret + "");
        if (getmsg != null && getmsg.Trim() != "")
        {
            try
            {
                //解析订单明细的josn
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                JsonObject_token jt = serializer.Deserialize<JsonObject_token>(getmsg);
                if (jt != null)
                {
                    //enddate = DateTime.Now.AddSeconds(Convert.ToInt32(jt.expires_in));
                    enddate = DateTime.Now.AddSeconds(120);
                    return jt.access_token;
                }
                return "";
            }
            catch (Exception)
            {
                return "";
            }
        }
        return "";
    }
    /// <summary>
    /// 获取jstoken凭证
    /// </summary>
    /// <returns></returns>
    public string getjstoken()
    {
        if (jsenddate == null || jstoken == null)
        {
            jsenddate = DateTime.Now;
        }
        if (DateTime.Now >= jsenddate)
        {
            jstoken = GetModel("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + getwxtokan());

        }
        //jstoken = GetModel("https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" + getwxtokan());
        if (jstoken != null && jstoken.Trim() != "")
        {
            try
            {
                //解析订单明细的josn
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                JsonObject_jstoken jstk = serializer.Deserialize<JsonObject_jstoken>(jstoken);
                if (jstk != null)
                {
                    //jsenddate = DateTime.Now.AddSeconds(Convert.ToInt32(jstk.expires_in));
                    jsenddate = DateTime.Now.AddSeconds(120);
                    return jstk.ticket;
                }
                return "";
            }
            catch (Exception)
            {
                return "";
            }
        }
        return "";
    }
    /// <summary>
    /// 发送文字消息
    /// </summary>
    /// <param name="wxopenid">接收者微信openid</param>
    /// <param name="msgtext">发送文字消息内容</param>
    public void sendwxText(string wxopenid, string msgtext)
    {
        string msg = "{\"touser\": \"" + wxopenid + "\","
                       + "\"msgtype\": \"text\","
                       + "\"text\": {\"content\": \"" + msgtext + "\"}}";


        PostModel("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + getwxtokan(), msg);
    }
    //图文消息条数限制在10条以内，注意，如果图文数超过10，则将会无响应。
    /// <summary>
    /// 发送图文消息 
    /// </summary>
    /// <param name="wxopenid">接收者微信openid</param>
    /// <param name="title">标题</param>
    /// <param name="text">内容</param>
    /// <param name="url">转跳到url</param>
    /// <param name="photourl">图片地址</param>
    public void sendwxImg(string wxopenid, string title, string text, string url, string photourl)
    {
        string msg = "{\"touser\": \"" + wxopenid + "\","
                       + "\"msgtype\": \"news\","
                       + "\"news\":{"
                       + "\"articles\": ["
                         + "{"
                            + "\"title\":\"" + title + "\","
                            + "\"description\":\"" + text + "\","
                            + "\"url\":\"" + url + "&r=" + Guid.NewGuid().ToString() + "\","
                            + "\"picurl\":\"" + photourl + "\""
                         + "}"
                       + "]"
                      + "}";

        PostModel("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + getwxtokan(), msg);
    }
    // 发送兑换订单消息模板  默认传跳到我的订单页面
    /// <summary>
    /// 发送兑换订单消息模板 默认传跳到我的订单页面
    /// </summary>
    /// <param name="wxopenid">接收者微信openid</param>
    /// <param name="title">主题</param>
    /// <param name="text1">姓名，卡号，内容</param>
    public void sendwxTemplate(string wxopenid, string title, string text_XM, string text_KH, string text)
    {
        string msg = "{"
           + "\"touser\":\"" + wxopenid + "\","
           + "\"template_id\":\"2xCGe6j61e3gEPeOLA0CBxN8-lZAPvx5el5rYc12lkE\","
           + "\"url\":\"http://oa.marino.com.cn/VIP/search.html?openid=" + wxopenid + "&r=" + Guid.NewGuid().ToString() + "\","
           + "\"topcolor\":\"#00FF00\","
           + "\"data\":{"
                    + "\"first\": {"
                      + " \"value\":\"" + title + " \\n\","
                      + " \"color\":\"#3300ff\""
                    + "},"
                    + "\"XM\":{"
                        + "\"value\":\"" + text_XM + "\","
                        + "\"color\":\"#fff\""
                    + "},"
                    + "\"KH\": {"
                        + " \"value\":\"" + text_KH + "\","
                        + "\"color\":\"#fff\""
                    + "},"
                    + "\"CONTENTS\":{"
                         + " \"value\":\"" + text + "\","
                         + "\"color\":\"#fff\""
                         + "},"
                    + "\"remark\":{"
                         + " \"value\":\"\\n 感谢您对马连奴的支持！\","
                         + "\"color\":\"#3300ff\""
                    + "}"
                + " }"
             + " }";

        PostModel("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getwxtokan(), msg);
    }

    // 重载发送兑换订单消息模板 可以传入转跳url，默认转跳到我的订单页面
    /// <summary>
    /// 重载发送兑换订单消息模板 可以传入转跳url，默认转跳到我的订单页面
    /// </summary>
    /// <param name="wxopenid">接收者微信openid</param>
    /// <param name="title">主题</param>
    /// <param name="text1">姓名，卡号，内容</param>
    public void sendwxTemplate(string wxopenid, string title, string text_XM, string text_KH, string text, string url)
    {
        if (url.Trim() == "")
        {
            url = "http://oa.marino.com.cn/VIP/search.html?openid=" + wxopenid + "&r=" + Guid.NewGuid().ToString();
        }
        string msg = "{"
           + "\"touser\":\"" + wxopenid + "\","
           + "\"template_id\":\"2xCGe6j61e3gEPeOLA0CBxN8-lZAPvx5el5rYc12lkE\","
           + "\"url\":\"" + url + "\","
           + "\"topcolor\":\"#00FF00\","
           + "\"data\":{"
                    + "\"first\": {"
                      + " \"value\":\"" + title + " \\n\","
                      + " \"color\":\"#3300ff\""
                    + "},"
                    + "\"XM\":{"
                        + "\"value\":\"" + text_XM + "\","
                        + "\"color\":\"#fff\""
                    + "},"
                    + "\"KH\": {"
                        + " \"value\":\"" + text_KH + "\","
                        + "\"color\":\"#fff\""
                    + "},"
                    + "\"CONTENTS\":{"
                         + " \"value\":\"" + text + "\","
                         + "\"color\":\"#fff\""
                         + "},"
                    + "\"remark\":{"
                         + " \"value\":\"\\n 感谢您对马连奴的支持！\","
                         + "\"color\":\"#3300ff\""
                    + "}"
                + " }"
             + " }";

        PostModel("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + getwxtokan(), msg);
    }

    /// <summary>
    /// get方法
    /// </summary>
    /// <param name="strUrl">传入url</param>
    /// <returns></returns>
    public string GetModel(string strUrl)
    {
        string strRet = null;
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
            request.Timeout = 2000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            System.IO.Stream resStream = response.GetResponseStream();
            Encoding encode = System.Text.Encoding.UTF8;
            StreamReader readStream = new StreamReader(resStream, encode);
            Char[] read = new Char[256];
            int count = readStream.Read(read, 0, 256);
            while (count > 0)
            {
                String str = new String(read, 0, count);
                strRet = strRet + str;
                count = readStream.Read(read, 0, 256);
            }
            resStream.Close();
        }
        catch (Exception e)
        {
            strRet = "";
        }
        return strRet;
    }
    /// <summary>
    /// post方法
    /// </summary>
    /// <param name="strUrl">传入url</param>
    /// <param name="strParm">传入参数</param>
    /// <returns></returns>
    public string PostModel(string strUrl, string strParm)
    {
        Encoding encode = System.Text.Encoding.UTF8;
        byte[] arrB = encode.GetBytes(strParm);

        HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(strUrl);
        myReq.Method = "POST";
        myReq.ContentType = "application/x-www-form-urlencoded";
        myReq.ContentLength = arrB.Length;
        Stream outStream = myReq.GetRequestStream();
        outStream.Write(arrB, 0, arrB.Length);
        outStream.Close();
        WebResponse myResp = null;
        try
        {
            //接收HTTP做出的响应
            myResp = myReq.GetResponse();
        }
        catch (Exception e)
        {
            int ii = 0;
        }
        Stream ReceiveStream = myResp.GetResponseStream();
        StreamReader readStream = new StreamReader(ReceiveStream, encode);
        Char[] read = new Char[256];
        int count = readStream.Read(read, 0, 256);
        string str = null;
        while (count > 0)
        {
            str += new String(read, 0, count);
            count = readStream.Read(read, 0, 256);
        }
        readStream.Close();
        myResp.Close();
        return str;
    }


    /// <summary>
    /// token的实体类
    /// </summary>
    public class JsonObject_token
    {
        public string access_token { get; set; }
        public string expires_in { get; set; }
    }

    /// <summary>
    /// jstoken的实体类
    /// </summary>
    public class JsonObject_jstoken
    {
        public string errcode { get; set; }
        public string errmsg { get; set; }
        public string ticket { get; set; }
        public string expires_in { get; set; }
    }

}